<template>
  <div>
    <div
      class="image-canvas-wrapper"
      unselectable="on">
      <span id="loadProgress">Diocm加载: </span>
      <div ref="canvas" class="image-canvas" oncontextmenu="return false"></div>
    </div>
  </div>
</template>

<script>
//引入 cornerstone,dicomParser,cornerstoneWADOImageLoader
import * as cornerstone from "cornerstone-core"
import * as dicomParser from "dicom-parser"

// 不建议 npm 安装 cornerstoneWADOImageLoader 如果你做了 会很头疼
import * as cornerstoneWADOImageLoader from "../../static/dist/cornerstoneWADOImageLoader.js"

// Cornerstone 工具外部依赖
import Hammer from "hammerjs"
import * as cornerstoneMath from "cornerstone-math"
import * as cornerstoneTools from "cornerstone-tools"

// Specify external dependencies
cornerstoneTools.external.Hammer = Hammer
cornerstoneTools.external.cornerstone = cornerstone
cornerstoneTools.external.cornerstoneMath = cornerstoneMath
cornerstoneTools.init(
  {
    mouseEnabled: true,
    touchEnabled: true,
    globalToolSyncEnabled: false,
    showSVGCursors: false,
  },
  {
    // 这里的配置项用于裁剪功能
    moduleName: "segmentation",
    configuration: {
      outlineWidth: 2,
    },
  }
)

const { setters, getters } = cornerstoneTools.getModule("segmentation")
cornerstoneWADOImageLoader.external.cornerstoneMath = cornerstoneMath

//指定要注册加载程序的基石实例
cornerstoneWADOImageLoader.external.cornerstone = cornerstone

cornerstone.registerImageLoader("http", cornerstoneWADOImageLoader.loadImage)
cornerstone.registerImageLoader("https", cornerstoneWADOImageLoader.loadImage)

//配置 webWorker (必须配置)
//注意这里的路径问题  如果路径不对 cornerstoneWADOImageLoaderWebWorker 会报错 index.html Uncaught SyntaxError: Unexpected token <
// var config = {
//   webWorkerPath: "../../static/dist/cornerstoneWADOImageLoaderWebWorker.js",
//   taskConfiguration: {
//     decodeTask: {
//       codecsPath: "../../static/dist/cornerstoneWADOImageLoaderCodecs.js",
//     },
//   },
// }
// cornerstoneWADOImageLoader.webWorkerManager.initialize(config)

export default {
  name: "HelloWorld",
  data() {
    return {
      element: null,
      selected: "",
      ImageIds: [
        "wadouri:http://127.0.0.1:5500/src/assets/dcm/1.2.840.113619.2.391.61490.1694724847.21.1.512.dcm",
        "wadouri:http://127.0.0.1:5500/src/assets/dcm/1.2.840.113619.2.391.61490.1694725120.22.1.512.dcm",
        "wadouri:http://127.0.0.1:5500/src/assets/dcm/1.2.840.113619.2.391.61490.1694725133.23.1.512.dcm",
      ],
      isInitLoad: true,
      isShow: true,
      tools: [],
      name: {
        PanTool: "Pan",
        LengthTool: "Length",
        MagnifyTool: "Magnify",
        AngleTool: "Angle",
        FreehandScissorsTool: "FreehandScissors",
        CircleScissorsTool: "CircleScissors",
        RectangleScissorsTool: "RectangleScissors",
        StackScrollMouseWheelTool: "StackScrollMouseWheel",
        StackScrollTool: "StackScroll",
      },
    }
  },
  methods: {
    show() {
      if (this.isShow === true) {
        this.isShow = false
        // 找到要渲染的元素
        this.element = this.$refs.canvas
        // 在 DOM 中将 canvas 元素注册到 cornerstone
        cornerstone.enable(this.element)
        // const viewport = cornerstone.getViewport(this.element)
        // 拼接 url : cornerstoneWADOImageLoader 需要 wadouri 路径头
        // stack，使用裁剪功能需要的东西，Segmentation required
        const stack = {
          currentImageIdIndex: 0,
          imageIds: this.ImageIds,
        }
        //  Load & Display
        cornerstone.loadAndCacheImage(this.ImageIds[0]).then(
          (image) => {
            // 设置元素视口
            var viewport = cornerstone.getDefaultViewportForImage(
              this.element,
              image
            )
            // 显示图像
            cornerstone.displayImage(this.element, image, viewport)
            cornerstoneTools.addStackStateManager(this.element, ["stack"]) // Segmentation required
            cornerstoneTools.addToolState(this.element, "stack", stack) // Segmentation required
            cornerstone.displayImage(this.element, image)
            cornerstone.setViewport(this.element, viewport)
            // default add zoom tool to ALL currently Enabled elements
            // cornerstoneTools.addTool(cornerstoneTools.ZoomMouseWheelTool);
            // cornerstoneTools.setToolActive('ZoomMouseWheel', { mouseButtonMask: 1 })
            cornerstoneTools.addTool(cornerstoneTools.StackScrollMouseWheelTool)
            cornerstoneTools.setToolActive("StackScrollMouseWheel", {
              mouseButtonMask: 1,
            })
            // 激活工具
            // this.activeTool('StackScrollMouseWheelTool')
          },
          function (err) {
            alert(err)
          }
        )

        // Dicom 加载 进度
        cornerstone.events.addEventListener(
          "cornerstoneimageloadprogress",
          (event) => {
            const eventData = event.detail
            const loadProgress = document.getElementById("loadProgress")
            loadProgress.textContent = `Dicom加载: ${eventData.percentComplete}%`
          }
        )
      } else {
        this.isShow = true
      }
    },
    activeTool(tool) {
      // Adds tool to ALL currently Enabled elements
      this.selected = tool
      /*
        下面是将裁剪工具设置为FILL_INSIDE，也就是内部填充
        还有属性：
            FILL_OUTSIDE: 外部填充,
            ERASE_OUTSIDE: 擦除外部,
            ERASE_INSIDE: 擦除内部,
    */
      if (tool.includes("Scissors")) {
        cornerstoneTools.addTool(this.tools[tool], {
          defaultStrategy: "FILL_INSIDE",
        })
      } else {
        cornerstoneTools.addTool(this.tools[tool])
      }
      cornerstoneTools.setToolEnabled(this.name[tool], { mouseButtonMask: 1 })
      cornerstoneTools.setToolActive(this.name[tool], { mouseButtonMask: 1 })
    },
    clearAllTool() {
      for (let k in this.name) {
        cornerstoneTools.clearToolState(this.element, this.name[k])
      }
      // 写了他才能让界面也更新清除了tool的视图
      cornerstone.updateImage(this.element)
      // reset viewport将视图重置位置
      cornerstone.reset(this.element)
    },
    initCanvasTools() {
      this.isInitLoad = false
      // 为 canvasStack 找到 imageIds
      let allImageIds = []
      this.ImageIds.forEach((imageId) => {
        let imageUrl = "wadouri:" + imageId
        allImageIds.push(imageUrl)
      })

      // Create canvasStack
      let canvasStack = {
        currentImageIdIndex: 0,
        imageIds: allImageIds,
      }

      // Add our tool, and set it's mode
      // const WwwcTool = cornerstoneTools.WwwcTool
      // cornerstoneTools.addTool(WwwcTool)
      // cornerstoneTools.setToolActive("Wwwc", { mouseButtonMask: 1 })
      // const MagnifyTool = cornerstoneTools.MagnifyTool
      // cornerstoneTools.addTool(MagnifyTool)
      // cornerstoneTools.setToolActive("Magnify", { mouseButtonMask: 1 })
      const StackScrollMouseWheelTool =
        cornerstoneTools.StackScrollMouseWheelTool
      cornerstoneTools.addTool(StackScrollMouseWheelTool)
      cornerstoneTools.setToolActive("StackScrollMouseWheel", {
        mouseButtonMask: 1,
      })

      // Enable Inputs
      // cornerstoneTools.mouseInput.enable(canvas)
      // cornerstoneTools.mouseWheelInput.enable(canvas)
      // cornerstoneTools.touchInput.enable(canvas)

      // Set the stack as tool state
      cornerstoneTools.addStackStateManager(this.element, ["stack"])
      cornerstoneTools.addToolState(this.element, "stack", canvasStack)
      // cornerstoneTools.stackScrollWheel.activate(canvas) // Mouse wheel
      // cornerstoneTools.scrollIndicator.enable(canvas) // Position indicator

      // Mouse
      // cornerstoneTools.wwwc.activate(canvas, 1) // left click
      // cornerstoneTools.pan.activate(canvas, 2) // middle click
      // cornerstoneTools.zoom.activate(canvas, 4) // right click

      // Touch / Gesture
      // cornerstoneTools.wwwcTouchDrag.activate(canvas) // - Drag
      // cornerstoneTools.zoomTouchPinch.activate(canvas) // - Pinch
      // cornerstoneTools.panMultiTouch.activate(canvas) // - Multi (x2)
    },
    /*
     * Window Resize
     *
     */
    listenForWindowResize() {
      this.$nextTick(() => {
        window.addEventListener(
          "resize",
          this.debounce(this.onWindowResize, 100)
        )
      })
    },
    onWindowResize() {
      cornerstone.resize(this.$refs.canvas, true)
    },
    /*
     * Utility Methods
     *
     */
    debounce(func, wait, immediate) {
      var timeout
      return function () {
        var context = this
        var args = arguments
        var later = function () {
          timeout = null
          if (!immediate) func.apply(context, args)
        }
        var callNow = immediate && !timeout
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
        if (callNow) func.apply(context, args)
      }
    },
  },
  mounted() {
    this.tools = {
      PanTool: cornerstoneTools.PanTool,
      LengthTool: cornerstoneTools.LengthTool,
      MagnifyTool: cornerstoneTools.MagnifyTool,
      AngleTool: cornerstoneTools.AngleTool,
      FreehandScissorsTool: cornerstoneTools.FreehandScissorsTool,
      CircleScissorsTool: cornerstoneTools.CircleScissorsTool,
      RectangleScissorsTool: cornerstoneTools.RectangleScissorsTool,
      StackScrollMouseWheelTool: cornerstoneTools.StackScrollMouseWheelTool,
      StackScrollTool: cornerstoneTools.StackScrollTool,
    }
    this.show()
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.image-canvas-wrapper {
  width: 100%;
  height: 80vh;
  margin: 0 auto;
}

.image-canvas {
  width: 100%;
  height: 100%;
}
</style>
